package service;

import dao.SchoolDao;
import domain.School;
import domain.University;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public class SchoolService {
    public static SchoolService schoolService = new SchoolService();
    public static SchoolDao schoolDao = new SchoolDao();
    public int count(University university) throws SQLException {
        return schoolDao.count(university);
    }

    public void add(School school) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        try {
            schoolDao.add(school, connection);
            System.out.println("添加成功");
            connection.commit();
        } catch (SQLException e) {
            System.out.println("添加失败");
            connection.rollback();
        } finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(null, connection);
        }

    }

    public boolean delete(int id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        return schoolDao.delete(id);
    }

    public String update(School school) throws SQLException {

        Connection connection = JdbcHelper.getConn();

        try {
            schoolDao.update(school);
            System.out.println("修改成功");
        } catch (SQLException e) {
            System.out.println("修改失败");
            e.printStackTrace();
        } finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(null, connection);
        }
        return null;
    }

    public Collection<School> findAll(List<Condition> conditionList, Pagination pagination) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Collection<School> schools = schoolDao.findAll(connection, conditionList, pagination);
        JdbcHelper.close(connection);
        return schools;
    }

    public static SchoolService getInstance() {
        return schoolService;
    }

    public School find(int university_id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        return SchoolDao.getInstance().find(university_id,connection);
    }
}
